package com.zx.map.utils;


import com.zx.platform.utils.StrUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by bibei on 2017/3/20.
 */
public class IPMacUtils {

	/**
	 * 获取请求IP
	 *
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		try {
			String ip = request.getHeader(" x-forwarded-for ");
			if (StrUtils.isBlank(ip)||" unknown ".equalsIgnoreCase(ip)) {
				ip = request.getHeader(" Proxy-Client-IP ");
			}
			if (StrUtils.isBlank(ip)|| " unknown ".equalsIgnoreCase(ip)) {
				ip = request.getHeader(" WL-Proxy-Client-IP ");
			}
			if (StrUtils.isBlank(ip) || " unknown ".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			return ip;
		} catch (Exception ex) {
			return "127.0.0.1";
		}
	}

	//获得IP
	public static InetAddress getInetAddress() {
		try {
			return InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			System.out.println("unknown host!");
		}
		return null;

	}

	public static String getHostIp(InetAddress netAddress) {
		if (null == netAddress) {
			//return null;
			netAddress = getInetAddress();
		}
		String ip = netAddress.getHostAddress(); // get the ip address
		return ip;
	}

	public static String getHostName(InetAddress netAddress) {
		if (null == netAddress) {
			//return null;
			netAddress = getInetAddress();
		}
		String name = netAddress.getHostName(); // get the host address
		return name;
	}
}
